package com.travelSpring.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.travelSpring.pojo.entity.User;
import com.travelSpring.exception.UserException;
import com.travelSpring.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 功能：
 * 作者：卷心菜
 * 日期：2025/3/27 16:34
 */
@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Resource
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        //从头获取token
        String token = request.getHeader("Authorization");
        if (token.startsWith("Bearer")) {
            token = token.substring(7);
        }
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("Authorization"); // 从URL参数获取
        }
        if (StrUtil.isBlank(token)) {
            throw new UserException("401", "未提供Token");
        }

        try {
            //拿到token的载荷数据
            String audience = JWT.decode(token).getAudience().get(0);
            String[] split = audience.split("-");
            String userId = split[0];
            String role = split[1];
            User exist = userService.selectById(userId);
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(exist.getPassword())).build();
            verifier.verify(token);
            if (StringUtils.isEmpty(userId)) {
                throw new UserException("无效Token");
            }
//            // 2. 安全转换
//            HandlerMethod handlerMethod = (HandlerMethod) handler;
//
//            // 3. 检查 @RequireAdmin 注解
//            boolean isAdminRequired = handlerMethod.getMethod().isAnnotationPresent(RequireAdmin.class)
//                    || handlerMethod.getBeanType().isAnnotationPresent(RequireAdmin.class);

            if (!"ADMIN".equals(role)) {
                throw new UserException("403", "无权访问，仅管理员可操作");
            }
            // 查询用户并验证
            User user = userService.selectById(userId);
            if (user == null) {
                throw new UserException("用户不存在");
            }
//            // 4. 存储用户信息到 request，供后续使用
//            request.setAttribute("currentUser", user);

            return true;
        }catch (TokenExpiredException e) {
            throw new UserException("401", "token 已过期，请重新登录");
        } catch (JWTVerificationException e) {
            throw new UserException("401", "token 无效");
        }
    }

}
